//
//  BDMyfriendTableViewCell.m
//  iOS_beboy
//
//  Created by Chuz NetTech on 17/10/20.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDMyfriendTableViewCell.h"
#import <YYKit.h>
#import <YYTextLayout.h>
#import "BDPostHelper.h"
#import "BDTextLinePositionModifier.h"
#import "JJPhotoManeger.h"

@interface BDMyfriendTableViewCell ()<JJPhotoDelegate>{
    CGFloat textHeight;
}

@property (nonatomic, strong) UIImageView *avatorImageView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIImageView *levelImageView;
@property (nonatomic, strong) UIImageView *vipImageView;
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) YYLabel *contextLabel;
@property (nonatomic, strong) UIImageView *imageView1;
@property (nonatomic, strong) BDMyDongTai *modelType;

@end

@implementation BDMyfriendTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    style = UITableViewCellStyleValue1;
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self.contentView addSubview:self.avatorImageView];
        [self.contentView addSubview:self.titleLabel];
        [self.contentView addSubview:self.levelImageView];
        [self.contentView addSubview:self.vipImageView];
        [self.contentView addSubview:self.contextLabel];
        [self.contentView addSubview:self.timeLabel];
        [self.contentView addSubview:self.imageView1];
    }
    return self;
}

-(void)layoutSubviews{
    [super layoutSubviews];
    
    _titleLabel.left = _avatorImageView.right + 10;
    _titleLabel.top = 20;
    [_titleLabel sizeToFit];
    
    self.levelImageView.size = CGSizeMake(22 / 2, 26 / 2);
    self.levelImageView.left = _titleLabel.right + 5;
    self.levelImageView.centerY = _titleLabel.centerY;
    
    self.vipImageView.size = CGSizeMake(34 / 2, 25 / 2);
    self.vipImageView.centerY = self.levelImageView.centerY;
    self.vipImageView.left = self.levelImageView.right + 5;
    
    
    _timeLabel.left = _titleLabel.left;
    _timeLabel.top = _titleLabel.bottom + 8;
    [_timeLabel sizeToFit];
    
    
    _contextLabel.left = 20;
    _contextLabel.top = _avatorImageView.bottom + 10;
    _contextLabel.size = CGSizeMake(kBDScreenWidth - 40, textHeight);
    
    for ( int i = 0; i < self.modelType.images.count; i++) {
        UIImageView *imageView = [self.contentView viewWithTag:100 + i];
        
        imageView.size = CGSizeMake((kBDScreenWidth - 80) / 3, (kBDScreenWidth - 80) / 3);
        imageView.left = _contextLabel.left + (imageView.width + 20) * (i % 3);
        imageView.top = _contextLabel.bottom + 10 + (imageView.height + 10) * (i / 3);
        
    }
    
}

- (void) tapProfileImage:(UITapGestureRecognizer *)gestureRecognizer{
    UIImageView *tableGridImage = (UIImageView*)gestureRecognizer.view;
    JJPhotoManeger *mg = [JJPhotoManeger maneger];
    mg.delegate = self;
    [mg showLocalPhotoViewer:@[tableGridImage] selecViewIndex:0];
}

-(void)photoViwerWilldealloc:(NSInteger)selecedImageViewIndex{
    
}

-(void)configData:(BDMyDongTai *)model{
    
    self.modelType = model;
    [self.avatorImageView sd_setImageWithURL:[NSURL URLWithString:model.user[@"cover"]] placeholderImage:[UIImage imageNamed:@"avatar"]];
    
    
    self.titleLabel.text = model.user[@"nickname"];
    
    self.levelImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"leve%ld",[model.points[@"level"] integerValue]]];
    
    self.vipImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@", [NSString stringWithFormat:@"showVip%ld",[model.user[@"vip_level"] integerValue]]]];
    
    NSDate *currentdate = [NSDate dateWithTimeIntervalSince1970:model.created_at.floatValue];
    
    NSDate *nowDate = [NSDate date];
    
    NSTimeInterval timeBetween = [nowDate timeIntervalSinceDate:currentdate];
    
    NSInteger timeValue = timeBetween;
    
    if (timeBetween < 60) {
        self.timeLabel.text = [NSString stringWithFormat:ASLocalizedString(@"%ld秒前"),timeValue];
    }else if (timeBetween < 3600){
        self.timeLabel.text = [NSString stringWithFormat:ASLocalizedString(@"%ld分钟前"),timeValue / 60];
    }else if (timeBetween < 24 * 3600){
        self.timeLabel.text = [NSString stringWithFormat:ASLocalizedString(@"%ld小时前"),timeValue / 3600];
    }else{
        self.timeLabel.text = [NSString stringWithFormat:ASLocalizedString(@"%ld月%ld日"),(long)currentdate.month,currentdate.day];
    }
    
    
    NSMutableAttributedString *text = [self _textWithPost:model.content
                                                 fontSize:12
                                                textColor:[UIColor colorWithHexString:@"666666"]];
    if (text.length == 0) return;
    BDTextLinePositionModifier *modifier = [BDTextLinePositionModifier new];
    modifier.font = [UIFont fontWithName:@"Heiti SC" size:12];
    modifier.paddingTop = 10;
    modifier.paddingBottom = 0;
    
    YYTextContainer *container = [YYTextContainer new];
    container.size = CGSizeMake(kBDScreenWidth - 20, MAXFLOAT);
    container.linePositionModifier = modifier;
    
    YYTextLayout *layout = [YYTextLayout layoutWithContainer:container text:text];
    if (!layout) return;
    
    textHeight = [modifier heightForLineCount:layout.rowCount];
    
    _contextLabel.attributedText = text;
    _contextLabel.numberOfLines = 0;
    
    
    for ( int i = 0; i < 9; i++) {
        UIImageView *imageView = [self.contentView viewWithTag:100 + i];
        if (i < model.images.count) {
            if (imageView) {
                [imageView sd_setImageWithURL:[NSURL URLWithString:model.images[i]] placeholderImage:[UIImage imageNamed:@"business_pic"]];
                
            }else{
                imageView = [[UIImageView alloc] init];
                [imageView sd_setImageWithURL:[NSURL URLWithString:model.images[i]] placeholderImage:[UIImage imageNamed:@"business_pic"]];
            }
            imageView.hidden = NO;
        }else{
            imageView.hidden = YES;
        }
        imageView.tag = 100 + i;
        [self.contentView addSubview:imageView];
        imageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapProfileImage:)];
        [imageView addGestureRecognizer:singleTap];
    }
    [[SDImageCache sharedImageCache] setValue:nil forKey:@"memCache"];
}

-(UIImageView *)avatorImageView{
    if (!_avatorImageView) {
        self.avatorImageView = [[UIImageView alloc] init];
        _avatorImageView.left = 20;
        _avatorImageView.top = 20;
        _avatorImageView.size = CGSizeMake(40, 40);
        _avatorImageView.layer.masksToBounds = YES;
        _avatorImageView.layer.cornerRadius = 20;
    }
    return _avatorImageView;
}

-(UILabel *)titleLabel{
    if (!_titleLabel) {
        self.titleLabel = [[UILabel alloc] init];
        _titleLabel.textColor = KBDColorBlue;
        _titleLabel.font = [UIFont systemFontOfSize:15];
    }
    return _titleLabel;
}

-(UIImageView *)levelImageView{
    if (!_levelImageView) {
        self.levelImageView = [[UIImageView alloc] init];
    }
    return _levelImageView;
}

- (UIImageView *)vipImageView{
    if (!_vipImageView) {
        self.vipImageView = [[UIImageView alloc] init];
    }
    return _vipImageView;
}

-(UILabel *)timeLabel{
    if (!_timeLabel) {
        self.timeLabel = [[UILabel alloc] init];
        _timeLabel.font = [UIFont systemFontOfSize:10];
        _timeLabel.textColor = [UIColor colorWithHexString:@"666666"];
    }
    return _timeLabel;
}

-(YYLabel *)contextLabel{
    if (!_contextLabel) {
        self.contextLabel = [[YYLabel alloc] init];
        _contextLabel.font = [UIFont systemFontOfSize:12];
        _contextLabel.textColor = [UIColor colorWithHexString:@"666666"];
    }
    return _contextLabel;
}



///对文本的处理
- (NSMutableAttributedString *)_textWithPost:(NSString *)contextString
                                    fontSize:(CGFloat)fontSize
                                   textColor:(UIColor *)textColor {
    if (!contextString) return nil;
    
    NSMutableString *string = contextString.mutableCopy;
    if (string.length == 0) return nil;
    
    // 字体
    UIFont *font = [UIFont systemFontOfSize:fontSize];
    // 高亮状态的背景
    YYTextBorder *highlightBorder = [YYTextBorder new];
    highlightBorder.insets = UIEdgeInsetsMake(-2, 0, -2, 0);
    highlightBorder.cornerRadius = 3;
    
    
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:string];
    text.font = font;
    text.color = textColor;
    
    //    // 根据 urlStruct 中每个 URL.shortURL 来匹配文本，将其替换为图标+友好描述
    //    for (WBURL *wburl in status.urlStruct) {
    //        if (wburl.shortURL.length == 0) continue;
    //        if (wburl.urlTitle.length == 0) continue;
    //        NSString *urlTitle = wburl.urlTitle;
    //        if (urlTitle.length > 27) {
    //            urlTitle = [[urlTitle substringToIndex:27] stringByAppendingString:YYTextTruncationToken];
    //        }
    //        NSRange searchRange = NSMakeRange(0, text.string.length);
    //        do {
    //            NSRange range = [text.string rangeOfString:wburl.shortURL options:kNilOptions range:searchRange];
    //            if (range.location == NSNotFound) break;
    //
    //            if (range.location + range.length == text.length) {
    //                if (status.pageInfo.pageID && wburl.pageID &&
    //                    [wburl.pageID isEqualToString:status.pageInfo.pageID]) {
    //                    if ((!isRetweet && !status.retweetedStatus) || isRetweet) {
    //                        if (status.pics.count == 0) {
    //                            [text replaceCharactersInRange:range withString:@""];
    //                            break; // cut the tail, show with card
    //                        }
    //                    }
    //                }
    //            }
    //
    //            if ([text attribute:YYTextHighlightAttributeName atIndex:range.location] == nil) {
    //
    //                // 替换的内容
    //                NSMutableAttributedString *replace = [[NSMutableAttributedString alloc] initWithString:urlTitle];
    //                if (wburl.urlTypePic.length) {
    //                    // 链接头部有个图片附件 (要从网络获取)
    //                    NSURL *picURL = [WBStatusHelper defaultURLForImageURL:wburl.urlTypePic];
    //                    UIImage *image = [[YYImageCache sharedCache] getImageForKey:picURL.absoluteString];
    //                    NSAttributedString *pic = (image && !wburl.pics.count) ? [self _attachmentWithFontSize:fontSize image:image shrink:YES] : [self _attachmentWithFontSize:fontSize imageURL:wburl.urlTypePic shrink:YES];
    //                    [replace insertAttributedString:pic atIndex:0];
    //                }
    //                replace.font = font;
    //                replace.color = kWBCellTextHighlightColor;
    //
    //                // 高亮状态
    //                YYTextHighlight *highlight = [YYTextHighlight new];
    //                [highlight setBackgroundBorder:highlightBorder];
    //                // 数据信息，用于稍后用户点击
    //                highlight.userInfo = @{kWBLinkURLName : wburl};
    //                [replace setTextHighlight:highlight range:NSMakeRange(0, replace.length)];
    //
    //                // 添加被替换的原始字符串，用于复制
    //                YYTextBackedString *backed = [YYTextBackedString stringWithString:[text.string substringWithRange:range]];
    //                [replace setTextBackedString:backed range:NSMakeRange(0, replace.length)];
    //
    //                // 替换
    //                [text replaceCharactersInRange:range withAttributedString:replace];
    //
    //                searchRange.location = searchRange.location + (replace.length ? replace.length : 1);
    //                if (searchRange.location + 1 >= text.length) break;
    //                searchRange.length = text.length - searchRange.location;
    //            } else {
    //                searchRange.location = searchRange.location + (searchRange.length ? searchRange.length : 1);
    //                if (searchRange.location + 1>= text.length) break;
    //                searchRange.length = text.length - searchRange.location;
    //            }
    //        } while (1);
    //    }
    //
    //    // 根据 topicStruct 中每个 Topic.topicTitle 来匹配文本，标记为话题
    //    for (WBTopic *topic in status.topicStruct) {
    //        if (topic.topicTitle.length == 0) continue;
    //        NSString *topicTitle = [NSString stringWithFormat:@"#%@#",topic.topicTitle];
    //        NSRange searchRange = NSMakeRange(0, text.string.length);
    //        do {
    //            NSRange range = [text.string rangeOfString:topicTitle options:kNilOptions range:searchRange];
    //            if (range.location == NSNotFound) break;
    //
    //            if ([text attribute:YYTextHighlightAttributeName atIndex:range.location] == nil) {
    //                [text setColor:kWBCellTextHighlightColor range:range];
    //
    //                // 高亮状态
    //                YYTextHighlight *highlight = [YYTextHighlight new];
    //                [highlight setBackgroundBorder:highlightBorder];
    //                // 数据信息，用于稍后用户点击
    //                highlight.userInfo = @{kWBLinkTopicName : topic};
    //                [text setTextHighlight:highlight range:range];
    //            }
    //            searchRange.location = searchRange.location + (searchRange.length ? searchRange.length : 1);
    //            if (searchRange.location + 1>= text.length) break;
    //            searchRange.length = text.length - searchRange.location;
    //        } while (1);
    //    }
    
    
    // 匹配 [表情]
    NSArray<NSTextCheckingResult *> *emoticonResults = [[BDPostHelper regexEmoticon] matchesInString:text.string options:kNilOptions range:text.rangeOfAll];
    NSUInteger emoClipLength = 0;
    for (NSTextCheckingResult *emo in emoticonResults) {
        if (emo.range.location == NSNotFound && emo.range.length <= 1) continue;
        NSRange range = emo.range;
        range.location -= emoClipLength;
        if ([text attribute:YYTextHighlightAttributeName atIndex:range.location]) continue;
        if ([text attribute:YYTextAttachmentAttributeName atIndex:range.location]) continue;
        NSString *emoString = [text.string substringWithRange:range];
        NSString *imageName = [BDPostHelper emoticonDic][emoString][@"gif"];
        
        UIImage *image = [BDPostHelper imageNamed:imageName];
        if (!image) continue;
        
        NSAttributedString *emoText = [NSAttributedString attachmentStringWithEmojiImage:image fontSize:fontSize];
        [text replaceCharactersInRange:range withAttributedString:emoText];
        emoClipLength += range.length - 1;
    }
    return text;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}

@end
